package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        //符合就生成六位数字验证码
        String code = RandomUtil.randomNumbers(6);
        //把验证码保存到redis里
       stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone, code);
        //发送验证码
        log.info("生成的验证码为:{}",code);
        //返回验证码
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //检验手机号，不符合返回错误
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        //获取验证码对比验证码如果不相等报错
        String code = loginForm.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        stringRedisTemplate.expire(RedisConstants.LOGIN_CODE_KEY + phone, 2, TimeUnit.MINUTES);
        if (cacheCode == null||!cacheCode.equals(code)) {

            return Result.fail("验证码错误");
        }
        //去数据库查询用户,如果不存在，创建用户
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user=createUserByphone(phone);
            save(user);
        }
        //保存用户到redis中
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String,Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString())
                );
       String tokenKey= RedisConstants.LOGIN_USER_KEY+ token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,map);
        //设置token有效期
        stringRedisTemplate.expire(tokenKey,30, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();
        //获取当天是本月的第几天
        String suffixKey = localDateTime.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        int dayOfMonth = localDateTime.getDayOfMonth();
        //拼接key
        String key=RedisConstants.USER_SIGN_KEY+userId+suffixKey;
        //写入redis中
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();
        //获取当天是本月的第几天
        String suffixKey = localDateTime.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        int dayOfMonth = localDateTime.getDayOfMonth();
        //拼接key
        String key=RedisConstants.USER_SIGN_KEY+userId+suffixKey;
        //获取截止到今天所有的签到情况bitField命令
        List<Long> list = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                .valueAt(0));
        if(list==null||list.isEmpty()){
            return Result.ok(0);
        }
        Long num = list.get(0);
        if(num==null||num==0){
            return Result.ok(0);
        }
        //让num与1进行与运算，再从后向前遍历(原理就是每次运算完将结果右移一位)，统计连续签到天数
        int count=0;
        while (true){
            if ((num&1)==0) {
                //今天没签到，直接结束
                break;
            }else {
                count++;
                num=num>>1;
            }
        }
        return Result.ok(count);
    }

    private User createUserByphone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        return user;
    }
}
